package logic

import (
	"bluebell/dao/mysql"
	"bluebell/models"
	"bluebell/pkg/jwt"
	snow "bluebell/pkg/sonwflake"
)

// 注册
func Sign(p *models.ParamSignUp) (err error) {
	// 1. 判断用户是否存在
	err = mysql.CheckUserExist(p.Username)
	if err != nil {
		// 数据库查询出错
		return err
	}
	// 2. 创建用户
	uid := snow.GenID()
	user := &models.User{
		UserID:   uid,
		Username: p.Username,
		Password: p.Password,
		Gender:   p.Gender,
		Email:    p.Email,
	}
	// 保存入库
	err = mysql.CreateUser(user)
	return err
}

// 登录
func Login(p *models.ParamsLogin) (user *models.User,
	token string, err error) {
	user = &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	if err = mysql.Login(user); err != nil {
		return
	}
	// 如果不出错的话，那么user 里面已经存入了需要的 user_id 字段了
	// 生成 JWT token
	token, err = jwt.GenToken(user.UserID, user.Username)
	return
}
